//
//  UIImage_Kit.swift
//  
//
//  Created by xp on 2023/4/3.
//

import UIKit

public extension UIImage {
    
    func redraw(size: CGSize,
                byRoundingCorners: UIRectCorner? = nil,
                cornerRadius: CGFloat? = nil,
                borderColor: UIColor? = nil,
                borderWidth: CGFloat? = nil,
                scale: CGFloat = UIScreen.main.scale) -> UIImage? {
        let width = borderWidth ?? 0
        let rect = CGRect(origin: .init(x: width/2, y: width/2), size: .init(width: size.width-width, height: size.height-width))
        defer {
            UIGraphicsEndImageContext()
        }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }
        
        if let byRoundingCorners = byRoundingCorners,
           let cornerRadii = cornerRadius {
            
            let bezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: byRoundingCorners, cornerRadii: .init(width: cornerRadii - width, height: cornerRadii - width))
            
            if let lineColor = borderColor,
               let lineWidth = borderWidth {
                lineColor.setStroke()
                bezierPath.lineWidth = lineWidth
                bezierPath.stroke()
            }
            
            context.addPath(bezierPath.cgPath)
        }
        context.clip()
        draw(in: rect)
        
        let result = UIGraphicsGetImageFromCurrentImageContext()
        
        return result
    }
    
    func getImageProperties() -> [String: Any]? {
        
        guard let data = pngData() else {
            return nil
        }
        let cfdata = data as CFData
        let options = [
            kCGImageSourceShouldCache: false,
            kCGImageSourceShouldAllowFloat: true
        ] as CFDictionary
        guard let source = CGImageSourceCreateWithData(cfdata, options) else {
            return nil
        }
        guard let props = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) else { return nil }
        return props as? [String: Any]
    }
}
